﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using IntelligentEscalator.BUS;
using IntelligentEscalator.DAL;
using IntelligentEscalator.Models;
using IntelligentEscalator.ElevatorWebSocket;
using Newtonsoft.Json;
using System.Runtime.Intrinsics.X86;
using NPOI.OpenXmlFormats.Wordprocessing;

namespace IntelligentEscalator.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class DeviceStateController : ControllerBase
    {
        private JwtSettings _jwtSettings;
        JwtToken _jwttoken = new JwtToken();
        IHttpContextAccessor _access;
        static IWebSocketManage _webSocketManage;
        private Dictionary<string, LiftStateALL> _dic;
        public DeviceStateController(IOptions<JwtSettings> jwtSettingsAccesser, IHttpContextAccessor access, IWebSocketManage webSocketManage
           )
        {
            _jwtSettings = jwtSettingsAccesser.Value;
            _access = access;
            _webSocketManage = webSocketManage;
        }

        /// <summary>
        /// 电梯状态设置缓存
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("SetStateMemory")]
        public ResponseMessage SetStateMemory()
        {
            ResponseMessage message = new ResponseMessage();
            ElevatorStateBUS BUS = new ElevatorStateBUS();
            LiftStateALL liftState = new LiftStateALL();
            LiftStateALL liftState2 = new LiftStateALL();
            int areaid = ElevatorWebSocketMiddleware.AreaId;
            int isall = ElevatorWebSocketMiddleware.IsAll;
            int elevatorid = ElevatorWebSocketMiddleware.Elevatorid;
            ElevatorAreaDAL da = new ElevatorAreaDAL();
            HttpContext context = _access.HttpContext;
            HttpRequest request = context.Request;
            string opcNO = string.Empty;
            string Car_position = string.Empty;
            string Car_door = string.Empty;
            string Moving_direction = string.Empty;
            string Elevator_control_status = string.Empty;
            string Full_load_alarm = string.Empty;
            string Car_load = string.Empty;
            string CarCall = string.Empty;
            string Landing_call_respond_up = string.Empty;
            string Landing_call_respond_down = string.Empty;
            string Faults = string.Empty;
            string Alarm_bell = string.Empty;
            string Elevator_running_state = string.Empty;
            string Car_position_index = string.Empty;
            try
            {
                if (request.Form.Keys.Count > 0)
                {
                    opcNO = request.Form["opcNO"];
                    liftState.opcNO = opcNO;
                    Car_position = request.Form["Car_position"];
                    liftState.Car_position = Car_position;
                    Car_door = request.Form["Car_door"];
                    liftState.Car_door = Car_door;
                    Moving_direction = request.Form["Moving_direction"];
                    liftState.Moving_direction = int.Parse(Moving_direction);
                    Elevator_control_status = request.Form["Elevator_control_status"];
                    liftState.Elevator_control_status = int.Parse(Elevator_control_status);
                    Full_load_alarm = request.Form["Full_load_alarm"];
                    liftState.Full_load_alarm = int.Parse(Full_load_alarm);
                    Car_load = request.Form["Car_load"];
                    liftState.Car_load = int.Parse(Car_load);
                    CarCall = request.Form["CarCall"];
                    liftState.CarCall = CarCall;
                    Landing_call_respond_up = request.Form["Landing_call_respond_up"];
                    liftState.Landing_call_respond_up = Landing_call_respond_up;
                    Landing_call_respond_down = request.Form["Landing_call_respond_down"];
                    liftState.Landing_call_respond_down = Landing_call_respond_down;
                    Faults = request.Form["Faults"];
                    liftState.Faults = int.Parse(Faults);
                    Alarm_bell = request.Form["Alarm_bell"];
                    liftState.Alarm_bell = int.Parse(Alarm_bell);
                    Elevator_running_state = request.Form["Elevator_running_state"];
                    liftState.Elevator_running_state = int.Parse(Elevator_running_state);
                    Car_position_index = request.Form["Car_position_index"];
                    liftState.Car_position_index = int.Parse(Car_position_index);
                    liftState.Elevator_control_statusName = ConvertStatuName(liftState.Elevator_control_status);
                    liftState.UpdateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    LogHelper.Print("电梯" + opcNO + ";Car_position:" + Car_position + ";Car_door:" + Car_door + ";Moving_direction:" + Moving_direction + ";Elevator_control_status:" + Elevator_control_status + ";Full_load_alarm:" + Full_load_alarm + ";Car_load:" + Car_load + ";CarCall:" + CarCall + ";Landing_call_respond_up:" + Landing_call_respond_up + ";Landing_call_respond_down:" + Landing_call_respond_down + ";Faults:" + Faults + ";Alarm_bell:" + Alarm_bell + ";Elevator_running_state:" + Elevator_running_state + ";Car_position_index:" + Car_position_index, opcNO);

                    List<AreaInfo> list = da.ShowAllArea(1);
                    message = BUS.ProcessData( liftState, out liftState2);
                    if (liftState2 != null)
                    {
                        #region new
                        if (liftState2.StatusChange == 1)
                        {
                            bool push = PushAreaMessage(liftState2.AreaID, liftState2).Result;
                            foreach (var item in list)
                            {
                                bool result = PushAreaMessage(item.id, liftState2).Result;
                            }
                            if (liftState2.Elevator_moving_status == 4)
                            {
                                //bool result4 = PushElevatorListMessage(liftState2).Result;
                            }
                        }
                        bool result2 = PushElevatorSingleMessage(liftState2.ElevatorID, liftState2).Result;

                        #endregion

                    }
                }
                else
                {
                    message.errcode = 1;
                    message.errmsg = "";
                }

            }
            catch (Exception e)
            {
                message.errcode = 1;
                message.errmsg = "设置缓存异常";
                message.data = null;
                message.total = 0;
                LogHelper.Log(e.ToString());
            }
            return message;
        }


        /// <summary>
        /// 电梯状态设置缓存
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("SetKoneStateMemory")]
        public ResponseMessage SetKoneStateMemory()
        {
            ResponseMessage message = new ResponseMessage();
            ElevatorStateBUS BUS = new ElevatorStateBUS();
            KoneDeviceStateSync koneDeviceStateSync = new KoneDeviceStateSync();
            HttpContext context = _access.HttpContext;
            HttpRequest request = context.Request;
            if (request.Form.Keys.Count > 0)
            {
            }
            koneDeviceStateSync.opcNO = request.Form["opcNO"];
            koneDeviceStateSync.Car_position = Convert.ToInt32(request.Form["Car_position"]);
            koneDeviceStateSync.Car_door = request.Form["Car_door"];
            koneDeviceStateSync.Moving_direction = Convert.ToInt32(request.Form["Moving_direction"]);
            koneDeviceStateSync.Elevator_control_status = Convert.ToInt32(request.Form["Elevator_control_status"]);
            koneDeviceStateSync.Full_load_alarm = Convert.ToInt32(request.Form["Full_load_alarm"]);
            koneDeviceStateSync.Car_load = Convert.ToInt32(request.Form["Car_load"]);
            koneDeviceStateSync.CarCall = request.Form["CarCall"];
            koneDeviceStateSync.Landing_call_respond_up = request.Form["Landing_call_respond_up"];
            koneDeviceStateSync.Landing_call_respond_down = request.Form["Landing_call_respond_down"];
            koneDeviceStateSync.Faults = Convert.ToInt32(request.Form["Faults"]);
            koneDeviceStateSync.Alarm_bell = Convert.ToInt32(request.Form["Alarm_bell"]);
            koneDeviceStateSync.Elevator_running_state = Convert.ToInt32(request.Form["Elevator_running_state"]);
            koneDeviceStateSync.updateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            try
            {

                ElevatorStateBUS elevatorStateBUS = new ElevatorStateBUS();
                elevatorStateBUS.MqttKoneDeviceSync(koneDeviceStateSync);
            }
            catch (Exception e)
            {
                message.errcode = 1;
                message.errmsg = "设置电梯状态异常";
                message.data = null;
                message.total = 0;
                LogHelper.Log(e.ToString());
            }
            return message;
        }

        public string ConvertStatuName(int status)
        {
            // string name = "OFL";
            string name = "在线";
            switch (status)
            {
                case 0:
                    //name = "NOR";
                    name = "正常";
                    break;
                case 99:
                    //name = "NOC";
                    name = "通讯断开";
                    break;
                /*  case 1:
                      name = "SRV";
                      break;*/
                case 2:
                    //name = "FRD";
                    name = "消防";
                    break;
                case 3:
                    //name = "STP";
                    name = "应急电源";
                    break;
                case 4:
                    //name = "ATS";
                    name = "司机";
                    break;
                case 7:
                    //name = "OSS";
                    name = "退出服务";
                    break;
                case 8:
                    //name = "PRC";
                    name = "运行";
                    break;
                case 14:
                    //name = "EFA";
                    name = "故障";
                    break;
                case 15:
                    //name = "PAD";
                    name = "驻停";
                    break;
                case 17:
                    //name = "DIS";
                    name = "正常";
                    break;
            }
            return name;
        }

        public async Task<bool> PushMessage(LiftStateALL liftState)
        {
            return await _webSocketManage.PushMessage(liftState);
        }

        public async Task<bool> PushElevatorMessage(LiftStateALL liftState)
        {
            return await _webSocketManage.PushElevatorMessage(liftState);
        }

        public async Task<bool> PushTwinkleMessage(LiftStateALL liftState)
        {
            return await _webSocketManage.PushTwinkleMessage(liftState);
        }
        public static async Task<bool> PushAreaMessage(int areaid, LiftStateALL liftState)
        {
            return await _webSocketManage.PushAreaMessage(areaid, liftState);
        }
        public async Task<bool> PushElevatorSingleMessage(int elevatorid, LiftStateALL liftState)
        {
            return await _webSocketManage.PushElevatorMessage(elevatorid, liftState);
        }

        public async Task<bool> PushElevatorListMessage(string msg)
        {
            return await _webSocketManage.PushElevatorListMessage(msg);
        }
    }
}
